package com.ruoyi.web.web.controller;

import com.ruoyi.web.core.config.AppConf;
import com.ruoyi.accountant.domain.AccountDetail;
import com.ruoyi.accountant.domain.ReasonDetail;
import com.ruoyi.accountant.domain.TransactionDetail;
import com.ruoyi.accountant.service.AccountDetailService;
import com.ruoyi.accountant.service.ReasonDetailService;
import com.ruoyi.accountant.service.TransactionDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/***
 * 文件相关
 */
@RestController
@RequestMapping("/file")
public class FileController {
    private Random random = new Random();
    @Autowired
    private TransactionDetailService transactionDetailService;
    @Autowired
    private AccountDetailService accountDetailService;

    @Autowired
    private ReasonDetailService reasonDetailService;


    /***
     * 下载文件
     * @param tid 交易记录详情ID
     * @param response
     *
     */
    @RequestMapping("/download")
    public void download(@RequestParam("tid") Long tid,@RequestParam("aid") Long aid, @RequestParam("rid") Long rid, HttpServletResponse response, HttpSession session) throws IOException {

        String attachment = null;
        if(tid != null) {
            TransactionDetail detail = transactionDetailService.findById(tid);
            attachment = detail.getAttachment();
        } else if(aid != null) {
            AccountDetail detail = accountDetailService.findById(aid);
            attachment = detail.getAttachment();
        } else if(rid != null) {
            ReasonDetail detail = reasonDetailService.findById(aid);
            attachment = detail.getAttachment();
        } else {
            return;
        }

        String path = AppConf.getUploadPath() + attachment.split(";")[0];
        File file = new File(path);

        if(file.exists()) {
            String fileName = file.getName().substring(file.getName().indexOf("-")+1);

            String mimeType = session.getServletContext().getMimeType(fileName);

            response.setContentType(mimeType);
            response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
            response.setContentLengthLong(file.length());

            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024 * 5]; int len = 0;
            while((len = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer,0, len);
                outputStream.flush();
            }
        }
    }


    /***
     * 上传文件
     * @param files
     */
    @RequestMapping("/upload")
    @ResponseBody
    public List<String> upload(MultipartFile[] files, HttpSession session) throws Exception {
        List<String> list = new ArrayList<>();
        for (MultipartFile file : files) {
            String level1 = (file.hashCode() &  0X3FF) + "";
            String level2 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";
            String level3 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";
            String level4 = (new Long((System.currentTimeMillis() + random.nextInt(1024))).hashCode() &  0X3FF) + "";

            String randomPath = level1 + "/" + level2 + "/" + level3 + "/" + level4+"/";
            if(!(new File(AppConf.getUploadPath()+randomPath).exists())) {
                new File(AppConf.getUploadPath()+randomPath).mkdirs();
            }

            String randomName = UUID.randomUUID().toString();
            randomPath += randomName.replace("-", "")+"-"+file.getOriginalFilename();

            File path = new File(AppConf.getUploadPath()+randomPath);

            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path));
            byte[] buffer = new byte[1024 * 5]; int len = 0;
            InputStream in = file.getInputStream();
            while((len = in.read(buffer)) != -1) {
                out.write(buffer,0,len);
                out.flush();
            }
            out.close();
//            IOUtils.copy(file.getInputStream(), new BufferedOutputStream(new FileOutputStream(path)));

            session.setAttribute(randomName, randomPath);
            list.add(randomName);
        }
        return list;
    }
}
